<?php

if (constant('APP_HTTP_HOST')=='uvm.local.com') {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
}

/*
 * Script kicking off the server
 */
extendIncludePath(dirname(__FILE__));

try {
    $frontCtl = new UvmFrontController($_SERVER, $_GET, $_POST, dirname(__FILE__));
    $frontCtl->dispatch();
} catch (Exception $xc) {
    $frontCtl->dispatch($xc);
}








/**
 * Adds path to PHP's auto include
 * 
 * @param string|false $add_path Path to add
 * 
 * @return bool
 */
function extendIncludePath($add_path)
{
    $orig = get_include_path();
    if (!is_bool(realpath($add_path)) && is_dir($add_path)) {
        $all = explode(PATH_SEPARATOR, $orig);
        if (isset($all[0]) && $all[0]=='.') {
            unset($all[0]);
        }
        $all[] = $add_path;
        $mod   = '.'.join(PATH_SEPARATOR, $all);
        
        set_include_path($mod);
        
        return (strlen(get_include_path())>strlen($orig));
    }
}

/**
 * Auto-loader for PHP classes 
 * 
 * @param string $class Name of the class to be loaded
 * 
 * @return void 
 * 
 */
function __autoload($class)
{
    if (!is_bool(strpos($class, '_'))) {
        $class = str_replace('_', DIRECTORY_SEPARATOR, $class);
    }
    include_once $class.'.php';
    return;
}

/**
 * Creates output of the subject passed, by default halting further execution
 * 
 * @param mixed $subject Element that you need insight into
 * 
 * @param bool  $halt    Flag (optional) if TRUE execution halts after dump
 * 
 * @return void
 */
function trap($subject, $halt=true)
{
    $cli = (isset($_SERVER['TERM'])) ? true : false;
    
    try {
        throw new Exception('DUMMIE');
    } catch (Exception $xc) {
    }
    
    ob_start();
    var_dump($subject);
    $dump = ob_get_clean();
    
    $details = array(
        'Details'     => print_r($subject, true),
        'Dump'        => $dump,
        'Stack trace' => print_r($xc->getTrace(), true)
    );
    
    echo ($cli!==true) ? "<pre>" : chr(27)."[H".chr(27)."[2J"."\n";
    
    foreach ($details as $descr => $data) {
        
        if (true===$cli) {
            echo "\n\n------------- {$descr} -----------------\n\n{$data}\n";
        } else {
            echo "<h3>{$descr}</h3><br>{$data}<br>";
        }
    }
    
    echo ($cli!==true) ? "<pre>" : "\n";
    
    if ($halt===true) {
        exit();
    }
}

/**
 * Errors and warnings to exceptions...
 *
 * @param int    $errno      Number
 * @param string $errstr     String
 * @param mixed  $errfile    File
 * @param int    $errline    Line no.
 * @param null   $errcontext Context
 * 
 * @return throws exception message
 * 
 */
function dlbkErrorHandler($errno, $errstr, $errfile, $errline, $errcontext = null)
{
    throw New ErrorException($errstr, 0, $errno, $errfile, $errline);
}

